#include "dbmanager.h"

DBManager::DBManager()
    : m_gift()
{
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(Config::instance().host());
    db.setPort(Config::instance().port());
    db.setDatabaseName(Config::instance().dbName());
    db.setUserName(Config::instance().dbUserName());
    db.setPassword(Config::instance().dbPassword());

    if (!db.open()) {
        qDebug() << "Failed to open database:" << db.lastError().text();
    } else {
        qDebug() << "数据库已连接";
    }
}


DBManager::~DBManager()
{
    if (db.isOpen()) {
        db.close();
    }
}


bool DBManager::createTable(const QString &tableName, const QString &columns)
{
    QSqlQuery query;
    QString sql = QString("CREATE TABLE IF NOT EXISTS %1 (%2)").arg(tableName).arg(columns);

    if (!query.exec(sql))
    {
        qDebug() << "Failed to create table:" << query.lastError().text();
        return false;
    }

    return true;
}


bool DBManager::insertData(const QString &tableName, const QStringList &values)
{
    QSqlQuery query;
    QString placeholders = QString("?,").repeated(values.size() - 1) + "?";
    QString sql = QString("INSERT INTO %1 VALUES (%2)").arg(tableName).arg(placeholders);
    query.prepare(sql);

    for (const QString& value : values)
    {
        query.addBindValue(value);
    }

    if (!query.exec())
    {
        qDebug() << "Failed to insert data:" << query.lastError().text();
        return false;
    }

    return true;
}


QSqlQuery DBManager::selectData(const QString &tableName, const QString &columns, const QString &condition)
{
    QSqlQuery query;
    QString sql;

    if (db.isOpen()) {
        db.close();
        db.open();
    }

    sql = QString("SELECT %1 FROM %2 WHERE %3").arg(columns).arg(tableName).arg(condition);

    if (!query.exec(sql))
    {
        qDebug() << "Failed to select data:" << query.lastError().text();
    }

    return query;
}


int DBManager::get_code(const QString data)
{
    int code = 0;

    for (auto& gift : m_gift)
    {
        if (gift.name == data)
        {
            code = gift.id;
        }
    }

    return code;
}


// 获取游戏列表
QVector<GameData*> DBManager::get_games()
{
    QSqlQuery query;
    QString sql;
    QVector<GameData*> games;

    sql = QString("SELECT * FROM game");

    if (!query.exec(sql))
    {
        qDebug() << "Failed to select data:" << query.lastError().text();
    }
    else
    {
        while (query.next())
        {
            int id = query.value(0).toInt();
            QString gameName = query.value("gameName").toString();

            games.append(new GameData(id, gameName));
        }
    }
    return games;
}


// 解析 JSON 字符串并转换为 GiftData 对象存储在 QVector 中


// 传入游戏id获取该游戏的礼物配置
QVector<GiftData> DBManager::get_gift(int gameId)
{
    QString sqlQuery = R"(
        SELECT
            gt.id AS gift_id,
            gt.giftName AS gift_name,
            gt.real_value,
            gt.points,
            gg.config_id
        FROM
            game g
        LEFT JOIN
            game_gift gg ON g.id = gg.game_id
        LEFT JOIN
            gift gt ON gg.gift_id = gt.id
        WHERE
            g.id = ?;
    )";

    QSqlQuery query(db);
    query.prepare(sqlQuery);
    query.bindValue(0, gameId);

    if (!query.exec())
    {
        qDebug() << "查询执行失败:" << query.lastError().text();
        m_gift.clear();
    }


    // 处理查询结果
    while (query.next())
    {
        int giftId          = query.value("config_id").toInt();
        QString giftName    = query.value("gift_name").toString();

        m_gift.append(GiftData(giftId, giftName));
    }

    std::sort(m_gift.begin(), m_gift.end(),
      [](const auto& a, const auto& b) {
        return a.id < b.id;
    });

    return m_gift;
}

QString DBManager::get_gift_by_index(int index)
{
    if (index < 0 || index > this->m_gift.size() - 1)
    {
        return "";
    }

    return this->m_gift.at(index).name;
}


QVector<GiftData> DBManager::get_gift()
{
    return this->m_gift;
}

